/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	core "PcapCapture/src"
	"PcapCapture/src/options"
	"github.com/spf13/cobra"
	"os"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "CatchTool",
	Short: "这个工具可以自动扫描设备上的网络接口，完成抓包并保存",
	Long: `这个工具的运行逻辑如下
1. 通过pcap.FindAllDevs() 获得所有的网络接口
2. 筛选出其中的非空接口，开始监听数据包
3. 将监听到的数据包解析之后，保存在输出目录/Output/Device/[接口名].json中，格式如下：
{"timestamp":"0001-01-01T00:00:00Z",
"src_mac":"bc:09:1b:ea:bf:fa",
"dst_mac":"d4:da:21:5f:ca:2c",
"src_ip":"192.168.31.136",
"dst_ip":"8.8.8.8",
"protocol":"ICMPv4",
"payload_len":0}
4. `,
	PreRun: func(cmd *cobra.Command, args []string) {
		// 如果用户输入 --help，直接输出帮助并退出
		for _, arg := range os.Args {
			if arg == "--help" || arg == "-h" {
				err := cmd.Help()
				if err != nil {
					return
				}
				os.Exit(0)
			}
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		core.Run(fillter, waitTime, timeout, options.IpInfoLogOpt{
			CountryName:   CountryName,
			RegionName:    RegionName,
			CityName:      CityName,
			DistrictName:  DistrictName,
			OwnerDomain:   OwnerDomain,
			IspDomain:     IspDomain,
			CountryCode:   CountryCode,
			ContinentCode: ContinentCode,
		})
	},
}

var (
	fillter  string
	waitTime int
	timeout  int

	// ipInfo
	CountryName   bool
	RegionName    bool
	CityName      bool
	DistrictName  bool
	OwnerDomain   bool
	IspDomain     bool
	CountryCode   bool
	ContinentCode bool
)

func Execute() {
	err := rootCmd.Execute()

	if err != nil {
		os.Exit(1)
	}
}

func init() {
	// 给main 添加参数
	rootCmd.Flags().StringVarP(&fillter, "fillter", "f", "", "过滤器字符串")
	rootCmd.Flags().IntVarP(&waitTime, "waitTime", "T", 1, "工具运行时间，单位是min")
	rootCmd.Flags().IntVarP(&timeout, "timeOut", "t", 7000, "Handle超时时间,单位是ms")

	//IpInfoOpt
	// 布尔类型标志（用户只需输入标志即可设置为true）
	rootCmd.Flags().BoolVarP(&CountryName, "country-name", "C", false, "显示国家名称")
	rootCmd.Flags().BoolVarP(&RegionName, "region-name", "R", false, "显示地区名称")
	rootCmd.Flags().BoolVarP(&CityName, "city-name", "c", false, "显示城市名称")
	rootCmd.Flags().BoolVarP(&DistrictName, "district-name", "d", false, "显示区县名称")
	rootCmd.Flags().BoolVarP(&OwnerDomain, "owner-domain", "o", false, "显示所有者域名")
	rootCmd.Flags().BoolVarP(&IspDomain, "isp-domain", "i", false, "显示ISP域名")
	rootCmd.Flags().BoolVarP(&CountryCode, "country-code", "U", true, "显示国家代码")
	rootCmd.Flags().BoolVarP(&ContinentCode, "continent-code", "u", false, "显示大洲代码")
}
